//
//  ShareView.m
//  AnProject
//
//  Created by TobyYoung on 2017/5/23.
//  Copyright © 2017年 Answern. All rights reserved.
//

#import "ShareView.h"

#define kShareViewHeight           240

@interface ShareView() {
    
    UIControl *_blackViewControl;
    UIView *_whiteView;
}
@property (nonatomic, copy) ShareSuccessCallbackBlock shareSuccessBlock;
@property (nonatomic, copy) LoginSuccessCallbackBlock loginSuccessBlock;
@property (nonatomic, copy) PaySuccessCallbackBlock paySuccessBlock;
@property (nonatomic, strong) ShareModel *shareModel;

@end

@implementation ShareView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor clearColor];
        self.alpha = 0.0;
        
        // 半透明底
        _blackViewControl = [[UIControl alloc] initWithFrame:self.bounds];
        _blackViewControl.backgroundColor = [UIColor blackColor];
        _blackViewControl.alpha = 0.4;
        _blackViewControl.exclusiveTouch = YES;
        [_blackViewControl addTarget:self action:@selector(dismissShareView) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_blackViewControl];
        
        // 白色view
        UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, GHEIGHT - kShareViewHeight, GWIDTH, kShareViewHeight)];
        whiteView.backgroundColor = ColorWhite;
        [self addSubview:whiteView];
        _whiteView = whiteView;
        _whiteView.top = GHEIGHT;
        
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, GWIDTH, 20)];
        titleLab.backgroundColor = [UIColor clearColor];
        titleLab.font = PFRFONT(16);
        titleLab.textColor = COLOR_FOR_TEXT_4A;
        titleLab.text = @"分享到";
        titleLab.textAlignment = NSTextAlignmentCenter;
        [_whiteView addSubview:titleLab];

        for (int i = 0; i < 2; i++) {

            UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            shareBtn.backgroundColor = [UIColor clearColor];
            shareBtn.frame = CGRectMake(0, 67, 67, 67);
            shareBtn.exclusiveTouch = YES;
            [shareBtn addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            [_whiteView addSubview:shareBtn];
            
            UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, shareBtn.bottom+5, 80, 20)];
            titleLab.backgroundColor = [UIColor clearColor];
            titleLab.font = PFRFONT(14);
            titleLab.textColor = COLOR_FOR_TEXT_64;
            titleLab.textAlignment = NSTextAlignmentCenter;
            [_whiteView addSubview:titleLab];
            
            if (i == 0) {
                shareBtn.tag = WXSceneTimeline;//朋友圈
                shareBtn.centerX = floor(GWIDTH/4.0);
                [shareBtn setImage:IMAGE(@"share_friends") forState:UIControlStateNormal];
                titleLab.text = @"微信朋友圈";
            } else {
                shareBtn.tag = WXSceneSession;//好友列表
                shareBtn.centerX = floor(GWIDTH*3.0/4);
                [shareBtn setImage:IMAGE(@"share_weixin") forState:UIControlStateNormal];
                titleLab.text = @"微信好友";
            }

            titleLab.centerX = shareBtn.centerX;

        }
        
        // 取消按钮
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        cancelBtn.backgroundColor = [UIColor clearColor];
        cancelBtn.frame = CGRectMake(0, kShareViewHeight-52, GWIDTH, 52);
        cancelBtn.exclusiveTouch = YES;
        cancelBtn.titleLabel.font = PFRFONT(16);
        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cancelBtn setTitleColor:COLOR_FOR_STYLE forState:UIControlStateNormal];
//        [cancelBtn setTitleColor:COLOR_999999 forState:UIControlStateHighlighted];
        [cancelBtn addTarget:self action:@selector(dismissShareView) forControlEvents:UIControlEventTouchUpInside];
        [whiteView addSubview:cancelBtn];
        
        // 线
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, kShareViewHeight-52.5, GWIDTH, 0.5)];
        lineView.backgroundColor = ColorFrom16(0xe2e2e2);
        [whiteView addSubview:lineView];
        
    }
    return self;
}

- (void)dealloc{
    NSLog(@"%s",__PRETTY_FUNCTION__);
}

+ (ShareView *)sharedInstance {
    
    static ShareView *shareView = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        shareView = [[self alloc] initWithFrame:CGRectMake(0, 0, GWIDTH, GHEIGHT)];
    });
    return shareView;
}

// 分享
- (void)showShareViewWithModel:(ShareModel *)model andCallback:(ShareSuccessCallbackBlock)callback {
    
    if (model == nil) {
        return;
    }
    
    _shareModel = model;
    _shareSuccessBlock = callback;
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    
    [UIView animateWithDuration:0.3 animations:^(void){
        
        self.alpha = 1.0;
        _whiteView.top = GHEIGHT - kShareViewHeight;
        
    } completion:^(BOOL finished) {
        
        
    }];
}

- (void)shareBtnAction:(UIButton *)sender {
    
    // message  创建分享内容对象
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = STRING(_shareModel.title);
    message.description = STRING(_shareModel.desc);
    
    // icon
    NSString *iconUrlStr = STRING(_shareModel.imgUrl);
    if ([@"" isEqualToString:iconUrlStr]) {
        [message setThumbImage:[UIImage imageNamed:@"login_logo"]];//设置分享时候的log
    } else {
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:iconUrlStr]];
        ;
        data = UIImageJPEGRepresentation([UIImage imageWithData:data], 0.3);//压缩图片
//        UIImage *img = [self compressImage:[UIImage imageWithData:data] toByte:32];
//        data = UIImagePNGRepresentation(img);
        [message setThumbData:data];
    }
    
    // url 创建多媒体对象
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = STRING(_shareModel.link);
    message.mediaObject = ext;
    
    // send
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;//不使用文本信息
    req.message = message;
    req.scene = (enum WXScene)sender.tag;
    [WXApi sendReq:req];
    
    
    [self performSelector:@selector(dismissShareView) withObject:nil afterDelay:0.1];
}

- (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}


// 登录
- (void)loginWithWxInVC:(UIViewController *)vc andCallback:(LoginSuccessCallbackBlock)callback {
    
    _loginSuccessBlock = callback;
    
    SendAuthReq* req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo"; // @"post_timeline,sns"
    req.state = @"pailexiong";
    
    [WXApi sendAuthReq:req viewController:vc delegate:self];
}

// 支付
- (void)payWithWxDict:(NSDictionary *)dict andCallback:(PaySuccessCallbackBlock)callback {
    _paySuccessBlock = callback;

    PayReq* req     = [[PayReq alloc] init];
    req.openID      = dict[@"appid"];
    req.partnerId   = dict[@"partnerid"];
    req.prepayId    = dict[@"prepayid"];
    req.nonceStr    = dict[@"noncestr"];
    req.timeStamp   = [STRING(dict[@"timestamp"]) intValue];
    req.package     = dict[@"package"];
    req.sign        = dict[@"sign"];
    
    [WXApi sendReq:req];
}


- (BOOL)handleOpenURL:(NSURL *)url {
    
    return [WXApi handleOpenURL:url delegate:self];
}

#pragma mark - WXApiDelegate

-(void) onReq:(BaseReq*)req
{
    
}

//微信回调
-(void) onResp:(BaseResp*)resp
{
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        // 分享
        if (resp.errCode == WXSuccess) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (_shareSuccessBlock) {
                    _shareSuccessBlock();
                }
            });
        }
    } else if ([resp isKindOfClass:[SendAuthResp class]]) {

        // 授权
        if (resp.errCode == WXSuccess) {
            
            SendAuthResp *authResp = (SendAuthResp *)resp;
            [self getWxTokenWithCode:authResp.code];
        }
        
    } else if ([resp isKindOfClass:[PayResp class]]) {
        
        // 支付
        if (resp.errCode == WXSuccess) {
            
//            PayResp *payResp = (PayResp *)resp;
            MESSAGE_TOAST(@"支付成功");
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (_paySuccessBlock) {
                    _paySuccessBlock();
                }
            });
        }
    }
}

- (void)getWxTokenWithCode:(NSString *)code {
    
    [SVProgressHUD show];
    
//    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",kWeiXinId,kWeixinAppSecret,code];
    NSDictionary *param = @{@"code":code};
    @weakobj(self);
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/passport/login?code=%@", GW_Domain, code] parameters:param completionBlockWithSuccess:^(NSDictionary *resultDict) {
//        NSLog(@"%@", resultDict);
        @strongobj(self);
        if (self.loginSuccessBlock) {
            self.loginSuccessBlock(resultDict);
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD dismiss];
        }
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", errorMsg);
    }];
    
}

//- (void)getWxUserInfoWithDict:(NSDictionary *)dict {
//    
//    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",dict[@"access_token"],dict[@"openid"]];
//    [[BaseNetService new].httpSessionManager GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//        
//        //        progress(1.0*uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        if ([responseObject isKindOfClass:[NSDictionary class]]) {
//            
//            if (_loginSuccessBlock) {
//                _loginSuccessBlock((NSDictionary *)responseObject);
//            }
//        }
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//        
//    }];
//}

#pragma mark - other method

- (void)dismissShareView {
    
    [UIView animateWithDuration:0.3 animations:^(void){
        
        self.alpha = 0.0;
        _whiteView.top = GHEIGHT;
        
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

@end
